package com.buaa.schedule;


import cn.hutool.core.convert.Convert;
import cn.hutool.core.util.ReUtil;
import cn.hutool.core.util.StrUtil;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.buaa.entity.TrafficCaseInfo;
import com.buaa.mapper.TrafficCaseInfoMapper;
import lombok.RequiredArgsConstructor;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

import java.util.List;
import java.util.regex.Pattern;

@Component
@RequiredArgsConstructor
public class HandleTrafficTime {

    private final TrafficCaseInfoMapper trafficCaseInfoMapper;

    private final static Pattern PATTERN = Pattern.compile("[凌晨|下午|晚上]*(\\d{1,2})时(\\d{1,2})*[分|分钟]*[许]*", Pattern.DOTALL);

    @Scheduled(cron = "5 */1 * * * *")
    public void handle() {
        Page<TrafficCaseInfo> page = new Page<>(0, 5000);
        QueryWrapper<TrafficCaseInfo> queryWrapper = new QueryWrapper<>();
        page.setRecords(trafficCaseInfoMapper.selectList(queryWrapper.isNull("time")));
        List<TrafficCaseInfo> list = page.getRecords();
        if (list.isEmpty()) {
            return;
        }
        for (TrafficCaseInfo trafficCaseInfo : list) {
            String trafficTime = trafficCaseInfo.getTrafficTime();
            if (StrUtil.isEmpty(trafficTime)) {
                continue;
            }
            List<String> allPattern = ReUtil.getAllGroups(PATTERN, trafficTime);

            if (allPattern.size() < 3) {
                continue;
            }

            String theTrafficTime = this.getTheTrafficTime(trafficTime, allPattern.get(1), allPattern.get(2));
            TrafficCaseInfo entity = new TrafficCaseInfo();
            entity.setId(trafficCaseInfo.getId());
            entity.setTime(theTrafficTime);
            trafficCaseInfoMapper.updateById(entity);
        }
    }

    private String getTheTrafficTime(String trafficTime,String hour,String minute) {
        Integer m;
        if (minute == null) {
            m = 0;
        } else {
            m = Convert.toInt(minute);
        }
        Integer h = Convert.toInt(hour);
        if ((trafficTime.contains("下午") || trafficTime.contains("晚上")) && h < 12) {
            //如果时间描述不是24小时制，修正
            h += 12;
        }
        String newMinute;
        if (m >= 0 && m < 15) {
            newMinute = "0";
        } else if (m >= 15 && m < 30) {
            newMinute = "15";
        } else if (m >= 30 && m < 45) {
            newMinute = "30";
        } else {
            newMinute = "45";
        }
        return Convert.toStr(h) + ":" + newMinute;
    }
}
